package com.xoa.controller.budget;

import com.alibaba.fastjson.JSONObject;
import com.xoa.model.budget.BudgetItem;
import com.xoa.model.budget.BudgetLog;
import com.xoa.model.workflow.FlowRunAttach;
import com.xoa.service.budget.BudgetItemManageService;
import com.xoa.service.sys.SystemInfoService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/*
 * 预算管理Controller
 * */
@Controller
@RequestMapping("/budget")
public class budgetItemController {

    @Autowired
    private SystemInfoService systemInfoService;
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }

    @Autowired
    BudgetItemManageService budgetItemManageService;

    @RequestMapping("/budgetItemManage")
    public String budgetItemManage(HttpServletRequest request,HttpSession session) {
        try {
            Object locale = request.getSession().getAttribute("LOCALE_SESSION_ATTRIBUTE_NAME");
            String realPath = request.getSession().getServletContext().getRealPath("/");
            Map<String, String> map = systemInfoService.getSystemInfo(realPath, locale,request);
            if(map!=null&&map.size()>0){
                Iterator i = map.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    if(entry.getKey().equals("module")){
                        session.setAttribute("module",entry.getValue()) ;
                        break;
                    }

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "app/budget/budgetItemManage";
    }

    @RequestMapping("/newBudget")
    public String newBudget() {
        return "app/budget/newBudget";
    }

    @RequestMapping("/newdel")
    public String newdel() {
        return "app/budget/newdel";
    }

    @RequestMapping("/budgetExecution")
    public String budgetExecution() {
        return "app/budget/budgetExecution";
    }

    @RequestMapping("/budgetJournal")
    public String budgetJournal() {
        return "app/budget/budgetJournal";
    }

    @RequestMapping("/viewReport")
    public String viewReport() {
        return "app/budget/viewReport";
    }

    @RequestMapping("/budgetManagement")
    public String budgetManagement() {
        return "app/budget/budgetManagement";
    }

    @RequestMapping("/budgetTaiZhang")
    public String budgetTaiZhang() {
        return "app/budget/budgetTaiZhang";
    }

    @RequestMapping("/fileManagement")
    public String fileManagement() {
        return "app/budget/fileManagement";
    }

    @RequestMapping("/budgetApprove")
    public String budgetApprove() {
        return "app/budget/budgetApprove";
    }

    @RequestMapping("/budgetExecute")
    public String budgetExecute() {
        return "app/budget/budgetExecute";
    }

    @RequestMapping("/newjournal")
    public String newjournal() {
        return "app/budget/newjournal";
    }

    @RequestMapping("/newjournal1")
    public String newjournal1() {
        return "app/budget/newjournal1";
    }

    @RequestMapping("yearViewReport")
    public String yearViewReport() {
        return "app/budget/yearViewReport";
    }

    @RequestMapping("reportStatistics")
    public String reportStatistics() {
        return "app/budget/reportStatistics";
    }

    @RequestMapping("budgetaryStatistics")
    public String budgetaryStatistics() {
        return "app/budget/budgetaryStatistics";
    }

    @RequestMapping("detailStatistics")
    public String detailStatistics() {
        return "app/budget/detailStatistics";
    }

    @RequestMapping("outDetail")
    public String outDetail() {
        return "app/budget/outDetail";
    }

    @RequestMapping("/budgeSetting")
    public String budgeSetting() {
        return "app/budget/budgeSetting";
    }


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：新建预算项目
     * 参数说明：
     */

    @ResponseBody
    @RequestMapping(value = "/addBudgetItem")
    public ToJson<BudgetItem> addBudgetItem(HttpServletRequest request, BudgetItem budgetItem) {
        return budgetItemManageService.addBudgetItem(request, budgetItem);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id删除预算项目
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/delBudgetItemById")
    public ToJson<BudgetItem> delBudgetItemById(HttpServletRequest request, BudgetItem budgetItem, int type) {
        return budgetItemManageService.delBudgetItemById(request, budgetItem, type);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id修改预算项目
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/upBudgetItemById")
    public ToJson<BudgetItem> upBudgetItemById(HttpServletRequest request, BudgetItem budgetItem) {
        return budgetItemManageService.upBudgetItemById(request, budgetItem);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：查询全部预算项目
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/selAllBudget")
    public ToJson<BudgetItem> selAllBudget(boolean delFlag, BudgetItem budgetItem, HttpServletRequest request, Integer page, Integer pageSize, boolean useFlag) {
        return budgetItemManageService.selAllBudget(delFlag, budgetItem, request, page, pageSize, useFlag);
    }


    @ResponseBody
    @RequestMapping(value = "/delAttachById1")
    public ToJson<BudgetItem> delAttachById1(Integer budgetId) {
        return budgetItemManageService.delAttachById1(budgetId);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-11
     * 方法介绍：预算导入接口
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/importBudgetItem")
    public void importBudgetItem(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<BudgetItem> itemToJson = new ToJson<BudgetItem>(0, null);
        try {
            itemToJson = budgetItemManageService.importBudgetItem(request, response, file, session);
            response.setHeader("content-type", "text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream out = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");
            ow.write(JSONObject.toJSONString(itemToJson));
            ow.flush();
            ow.close();
        } catch (Exception e) {
            itemToJson.setMsg(e.getMessage());
        }
        return;
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-11
     * 方法介绍：预算导出接口
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/outputBudgetItem")
    public ToJson<BudgetItem> outputBudgetItem(BudgetItem budgetItem, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        return budgetItemManageService.outputBudgetItem(budgetItem, request, response, session);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-10
     * 方法介绍：根据Id查询预算项目
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping("/selBudgetItemById")
    public ToJson<BudgetItem> selBudgetItemById(Integer budgetId, HttpServletRequest request) {
        // 获取库
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        String company = "xoa" + SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId);
        if (SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId) == null) {
            company = "xoa1001";
        }
        return budgetItemManageService.selBudgetItemById(budgetId, company);
    }


    /**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：根据id查询日志
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping("/selBudgetLogById")
    public ToJson<BudgetLog> selBudgetLog(BudgetItem budgetItem, Integer page, Integer pageSize, boolean useFlag) {
        return budgetItemManageService.selBudgetLog(budgetItem, page, pageSize, useFlag);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：查询全部日志
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping("/selAllBudgetLog")
    public ToJson<BudgetLog> selAllBudgetLog(Integer page, Integer pageSize, boolean useFlag) {
        return budgetItemManageService.selAllBudgetLog(page, pageSize, useFlag);
    }

    /* *//**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：添加日志权限
     * 参数说明：
     *//*

    @ResponseBody
    @RequestMapping("/upBudgetLogSet")
    public ToJson<BudgetLog> upBudgetLogSet(String userIds, String userPrivIds){
        return budgetItemManageService.upBudgetLogSet(userIds,userPrivIds);
    }

    @ResponseBody
    @RequestMapping("/delBudgetLogById")
    public ToJson<BudgetLog> delBudgetLogSetById(Integer logId){
        return budgetItemManageService.delBudgetLogSetById(logId);
    }
    *//**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：删除所有人的权限
     * 参数说明：
     *//*
    @ResponseBody
    @RequestMapping("/delBudgetLog")
    public ToJson<Users> delBudgetLog(){
        return budgetItemManageService.delBudgetLog();
    }
    *//**
     * 创建人：贾志康
     * 创建时间：2018-5-16
     * 方法介绍：查询有权限的人
     * 参数说明：
     *//*
    @ResponseBody
    @RequestMapping("/selBudgetLogSet")
    public ToJson<Users> selBudgetLogSet(){
        return budgetItemManageService.selBudgetLogSet();
    }
*/

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-22
     * 方法介绍：查询全部文件
     * 参数说明：
     */

    @ResponseBody
    @RequestMapping("/selAllAttach")
    public ToJson<FlowRunAttach> selAllAttach(HttpServletRequest request, String attachmentName, Integer page, Integer pageSize, boolean useFlag) {
        return budgetItemManageService.selAllAttach(request, attachmentName, page, pageSize, useFlag);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-22
     * 方法介绍：根据Id删除文件
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping("/delAttachById")
    public ToJson<FlowRunAttach> delAttachById(Integer seqId) {
        return budgetItemManageService.delAttachById(seqId);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-23
     * 方法介绍：查询报表接口
     * 参数说明：
     */

    @ResponseBody
    @RequestMapping("/selStatement")
    public ToJson<BudgetItem> selStatement(HttpServletRequest request, BudgetItem budgetItem, String[] budgetItemNames, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize, @RequestParam(value = "useFlag", defaultValue = "true") boolean useFlag) {
        return budgetItemManageService.selStatement(request, budgetItem, page, pageSize, useFlag);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-23
     * 方法介绍：预算执行台账列表查询
     * 返回预算列表json
     */

    @ResponseBody
    @RequestMapping("/selStatement1")
    public ToJson<BudgetItem> selStatement1(HttpServletRequest request, String deptId, String itemExecuter,
                                            Date applicantBeginTime, Date applicantEndTime, Integer budgetItemId,
                                            String applicant, Integer page, Integer pageSize, boolean useFlag) {
        // 查询条件封装对象
        BudgetItem condition = new BudgetItem();
        // 申请人
        condition.setApplicant(applicant);
        //所属部门
        condition.setDeptId(deptId);
        //预算项目Id
        condition.setBudgetId(budgetItemId);
        //项目执行人:itemExecuter
        if (itemExecuter != null && !"".equals(itemExecuter)) {
            condition.setItemExecuter(itemExecuter);
        }
        if (applicantBeginTime != null) {
            condition.setApplicantBeginTime(applicantBeginTime);
        }
        if (applicantEndTime != null) {
            condition.setApplicantEndTime(applicantEndTime);
        }
        return budgetItemManageService.selStatement1(request, condition, page, pageSize, useFlag);
    }

    /**
     * 创建人：贾志康
     * 创建时间：2018-5-23
     * 方法介绍：报表导出接口
     * 参数说明：
     */
    @ResponseBody
    @RequestMapping(value = "/outputStatement")
    public ToJson<BudgetItem> outputStatement(String deptId, String itemExecuter, Date budgetItemEnddate, Date budgetItemBegindate, Integer budgetId/*,Integer page, Integer pageSize, boolean useFlag*/, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        BudgetItem budgetItem = new BudgetItem();

        budgetItem.setBudgetId(budgetId);
        budgetItem.setDeptId(deptId);
        if (!StringUtils.checkNull(itemExecuter) && !"undefined".equals(itemExecuter)) {
            budgetItem.setItemExecuter(itemExecuter);
        }
        if (budgetItemBegindate != null) {
            budgetItem.setBudgetItemEnddate(budgetItemBegindate);
        }
        if (budgetItemEnddate != null) {
            budgetItem.setBudgetItemEnddate(budgetItemEnddate);
        }
        return budgetItemManageService.outputStatement(budgetItem, request, response, session);
    }

    @ResponseBody
    @RequestMapping(value = "/selOneLineNo")
    public String selOneLineNo(String budgetItemName) {
        return budgetItemManageService.selOneLineNo(budgetItemName);
    }


    @ResponseBody
    @RequestMapping(value = "/upBudgetItemById1")
    public ToJson<BudgetItem> upBudgetItemById1(HttpServletRequest request, BudgetItem budgetItem) {
        return budgetItemManageService.upBudgetItemById1(request, budgetItem);
    }

    @ResponseBody
    @RequestMapping("/selStatistics")
    public ToJson<BudgetItem> selStatistics(BudgetItem budgetItem) {
        return budgetItemManageService.selStatistics(budgetItem);
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/10/23
     * 参数: runId
     * 说明: 工作流表单查询所有项目用的接口
     */
    @ResponseBody
    @RequestMapping(value = "/selAllBudgetFlow")
    public ToJson<BudgetItem> selAllBudgetFlow(HttpServletRequest request, Integer runId, Integer prcsId) {
        return budgetItemManageService.selAllBudgetFlow(request, runId, prcsId);
    }

    @ResponseBody
    @RequestMapping("/selBudgetItemByIdFlow")
    public ToJson<BudgetItem> selBudgetItemByIdFlow(Integer budgetId, Integer runId) {
        return budgetItemManageService.selBudgetItemByIdFlow(budgetId, runId);
    }

    @ResponseBody
    @RequestMapping("/generateBudgetNo")
    public Integer generateBudgetNo(HttpServletRequest request) {
        return budgetItemManageService.generateBudgetNo(request);
    }

    /**
     * 设置编辑权限
     *
     * @param users 用户id字符串
     * @param privs 角色名称字符串
     * @return 结果
     */
    @RequestMapping("/setEditAuth")
    @ResponseBody
    public ToJson setEditAuth(@RequestParam(value = "User", required = false) String users,
                              @RequestParam(value = "Priv", required = false) String privs) {
        try {
            budgetItemManageService.setEditAuth(users, privs);
        } catch (Exception e) {
            e.printStackTrace();
            return new ToJson(1, "error");
        }
        return new ToJson(0, "ok");
    }

    /**
     * 回显编辑权限
     *
     * @return 拥有权限的人员和角色名称
     */
    @RequestMapping("/seeEditAuth")
    @ResponseBody
    public ToJson seeEditAuth() {
        try {
            String[] result = budgetItemManageService.seeEditAuth();
            ToJson json = new ToJson(0, "ok");
            json.setObject(result);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return new ToJson(1, "error");
        }
    }
}
